﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;

namespace FrontEnd
{
	public partial class ClosableTabHeader : UserControl
	{
		#region EVENTS
		public event EventHandler<CancelEventArgs> Closing;
		public event EventHandler Closed;
		#endregion

		#region PROPERTIES

		public SQLQueryTab ParentTab { get; private set; }

		public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ClosableTabHeader), new PropertyMetadata("TabItem"));
		public string Title
		{
			get { return (string)GetValue(TitleProperty); }
			set { SetValue(TitleProperty, value); }
		}

		public static readonly DependencyProperty IsIndicatingChangeProperty = DependencyProperty.Register("IsIndicatingChange", typeof(bool), typeof(ClosableTabHeader), new PropertyMetadata(false));
		public bool IsIndicatingChange
		{
			get { return (bool)GetValue(IsIndicatingChangeProperty); }
			set { SetValue(IsIndicatingChangeProperty, value); }
		}
		#endregion

		#region CONSTRUCTOR(S)

		public ClosableTabHeader(SQLQueryTab parentTab)
		{
			InitializeComponent();
			this.ParentTab = parentTab;
			this.DataContext = this;
		}

		#endregion

		#region PUBLIC METHODS
		#endregion

		#region PRIVATE METHODS

		private void btnClose_MouseEnter(object sender, MouseEventArgs e)
		{
			btnClose.Foreground = Brushes.Red;
		}

		private void btnClose_MouseLeave(object sender, MouseEventArgs e)
		{
			btnClose.Foreground = Brushes.Black;
		}

		private void btnClose_Click(object sender, RoutedEventArgs e)
		{
			OnClosing();
		}

		protected void OnClosing()
		{
			bool subscriberCancelled = false;
			if (Closing != null)
			{
				var args = new CancelEventArgs();
				foreach (EventHandler<CancelEventArgs> del in Closing.GetInvocationList())
				{
					del(this, args);
					if (args.Cancel)
					{
						subscriberCancelled = true;
						break;
					}
				}
			}

			if (!subscriberCancelled)
				OnClosed();
		}

		protected void OnClosed()
		{
			if (Closed != null)
				Closed(this, EventArgs.Empty);
		}

		#endregion
	}
}
